<?php

/* Classe userManager */

require_once 'User.php';
require_once 'Base.php';

class UserManager
{
	private $_bdd;
	
	public function __construct(PDO $db) {
		$this->_bdd = $db;
	}
	
	// Renvoi l'id du dernier inscrit
	public function lastInsertedId() {
		$q = $this->_bdd->query('SELECT MAX(id) FROM users');
		return $q->fetch();
	}
	
	// Retourne vrai si l'utilisateur existe
	public function exists($email) {
		$q = $this->_bdd->prepare('SELECT COUNT(*) FROM users WHERE email = :email');
		$q->bindValue(':email', $email, PDO::PARAM_STR);
		$q->execute();
		if(!$q->fetchColumn(0))
			return false;
		else
			return true;
	}
	
	// Ajoute un utilisateur
	public function add(User $u) {
		$q = $this->_bdd->prepare("INSERT INTO users (email, password, phone) VALUES (:email, :pass, :phone)");
		$q->bindValue(':email', $u->getEmail(), PDO::PARAM_STR);
		$q->bindValue(':pass', $u->getPassword(), PDO::PARAM_STR);
        $q->bindValue(':phone', $u->getPhone(), PDO::PARAM_STR);
        $q->execute();
	}
	
	// Supprime un utilisateur
	public function delete(User $u) {
		$q = $this->_bdd->prepare('DELETE FROM users WHERE email = :email');
		$q->bindValue(':email', $u->getEmail());
		$q->execute();
	}
	
	// Charge les infos d'un user à partir de son id
	public function get($email) {
		$q = $this->_bdd->prepare('SELECT * FROM users WHERE email = :email');
		$q->bindValue(':email', $email, PDO::PARAM_STR);
		$q->execute();
		$data = $q->fetch(PDO::FETCH_ASSOC);
		if($data != null)
			return new User($data);
		else
			return false;
	}
	
	// Retourne la liste des utilisateurs
	public function getList() {
		$users = array();
		$q = $this->_bdd->query('SELECT * FROM users');
		while($data = $q->fetch(PDO::FETCH_ASSOC)) {
			$users[] = new User($data);
		}
		return $users;
	}
	
	// Mettre à jour un user
	public function update(User $u) {
		$q = $this->_bdd->prepare('UPDATE users SET password = :pass, phone = :phone WHERE email = :email');
        $q->bindValue(':pass', $u->getPassword(), PDO::PARAM_STR);
        $q->bindValue(':phone', $u->getPhone(), PDO::PARAM_STR);
		$q->execute();
	}
}

?>